package com.powernode.service.impl;

import com.powernode.Strategy.LoginStrategy;
import com.powernode.constant.AuthConstants;
import com.powernode.factory.LoginStrategyFactory;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 *
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private LoginStrategyFactory loginStrategyFactory;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 获取 请求对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        // 从约定好的位置获取请求类型logintype  ---> 得到是从前端 还是 小程序端 发送的请求
        String loginType = request.getHeader(AuthConstants.LOGIN_TYPE);  // sysUserLogin
        // 判断请求的来源
        /*if (loginType.equals(AuthConstants.SYS_USER_LOGIN)) {
            // xxx
        } else if (loginType.equals(AuthConstants.MEMBER_LOGIN)) {
            // xxx
        }*/
        // 优化方法
        //  判断登录类型是否有值
        if (!StringUtils.hasText(loginType)) {
            // 不存在, 直接抛出
            throw new InternalAuthenticationServiceException("非法请求 , 登录类型不匹配");
        }
        // 存在  --->  通过 工厂模式 + 策略模式 获取到 实例对象
        LoginStrategy instance = loginStrategyFactory.getInstance(loginType);

        return instance.realLogin(username);
    }
}
